package com.zhaopin.theswordreferstooffer;

/**
 * @author yin.peide
 * @date 2021-06-10 17:02
 * 面试题20： 顺时针打印矩阵
 */
public class Offer20 {

    public static void main(String[] args) {

        int[] attr1 = {1, 2, 3, 4,444,5555};
        int[] attr2 = {5, 6, 7, 8,666,7777};
        int[] attr3 = {9, 10, 11, 12,8888,9999};
        int[] attr4 = {13, 14, 15, 16,1111,2222};

        int[][] attr = {attr1, attr2, attr3, attr4};

        int[] newAttr = spiralOrder(attr);
        for (int i : newAttr) {
            System.out.print(i + " ");
        }
        System.out.println();

    }

    public static int[] spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            return new int[0];
        }

        //n是行高  m是列宽
        int n = matrix.length, m = matrix[0].length;
        int[] res = new int[m * n];
        int up = 0, down = n - 1;
        int left = 0, right = m - 1;
        int total = m * n;
        int index = 0;
        while (index < total) {
            //上面，从左往右打印
            for (int j = left; j <= right && index < total; j++) {
                res[index++] = matrix[up][j];
            }

            //右边，从上往下打印(注意这里i的取值范围)
            for (int i = up + 1; i <= down - 1 && index < total; i++) {
                res[index++] = matrix[i][right];
            }

            //下边，从右往左打印
            for (int j = right; j >= left && index < total; j--) {
                res[index++] = matrix[down][j];
            }

            //左边，从下往上打印(注意这里i的取值范围)
            for (int i = down - 1; i >= up + 1 && index < total; i--) {
                res[index++] = matrix[i][left];
            }

            left++;
            right--;
            up++;
            down--;
        }
        return res;
    }

}
